package com.example.sports_meet.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sports_meet.R;
import com.example.sports_meet.adapter.BookAdapter;
import com.example.sports_meet.entity.Book;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SecondFragment extends Fragment {

    // 定义 API 调用的参数和 URL
    private static final String API_KEY = "b35300cc87b1445189a0d2c796a807ed";
    private static final String API_URL = "https://openainut.openai.azure.com/openai/deployments/gpt35turbo/chat/completions?api-version=2023-03-15-preview";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_second, container, false);

        // 获取搜索栏和文本框
        SearchView searchView = root.findViewById(R.id.search);


        RecyclerView recyclerView = root.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 设置搜索栏的监听器
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 在搜索栏输入关键词后，执行异步任务来调用 API 并更新 UI 界面上的文本框
                new SearchTask(query).execute(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });


        List<Book> books = new ArrayList<>();
        books.add(new Book("Charlotte’s Web", "E.B. White", "https://mmbiz.qpic.cn/mmbiz_jpg/IqicDAGdXNibvdy2sRAB2fjYnrqWkF8DWZdiaOODmYYxMIdxKLCJicVlTYL3BibMrB6vxqhJEj0I0tuJHQE5LmLkYDA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1"));
        books.add(new Book("Mieko and the Fifth Treasure", "Eleanor Coerr", "https://mmbiz.qpic.cn/mmbiz_jpg/FqicCNgEmkohnRC4mIbWiaJFXcibTOfUogeNNK5IQb3Z3QoG2B2UCnJTLYBsY3BkElRjUZwEgepNaxjiaJ6dl42lRw/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1"));
        books.add(new Book("The Outsiders", "S.E. Hinton", "https://mmbiz.qpic.cn/mmbiz_jpg/IqicDAGdXNibvdy2sRAB2fjYnrqWkF8DWZ15kZ1UzQibM8FjEC05qRnL0mfg7jpV5NWKEECg7GdKMIWTFBdp8U1Fg/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1"));
        books.add(new Book("The House on Mango Street", "Sandra Cisneros ", "https://mmbiz.qpic.cn/mmbiz_jpg/IqicDAGdXNibvdy2sRAB2fjYnrqWkF8DWZxE5SXFjnlgksVCkbYSlmtR8vzNNDlMGcWoLwhVfiaOxFvw0BCsChyTw/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1"));
        books.add(new Book("Thirteen Reasons Why ", "Jay Asher", "https://mmbiz.qpic.cn/mmbiz_jpg/IqicDAGdXNibvdy2sRAB2fjYnrqWkF8DWZhRVoD9szbiaicYrSXmZb37DHCCibqlVceEA4ibicRsich6sq2KQ6HAeA78jA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1"));
        books.add(new Book("Peter Pan", "J.M. Barrie", "https://mmbiz.qpic.cn/mmbiz_jpg/FqicCNgEmkohnRC4mIbWiaJFXcibTOfUogeVoFs0uND3icf1cbnH1PYJllkJ533KQXkw3HcQHHA9kCohCbic0MMtSbQ/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1"));
        BookAdapter adapter = new BookAdapter(books, getContext());
        recyclerView.setAdapter(adapter);

        return root;
    }

    // 定义异步任务来执行 API 调用和 UI 更新操作
    private class SearchTask extends AsyncTask<String, Void, String> {

        private final String keyword;

        public SearchTask(String keyword) {
            this.keyword = keyword;
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                // 构造 API 请求体的 message 字段
                JSONObject message1 = new JSONObject();
                message1.put("role", "system");
                message1.put("content", "Write an English essay on this topic with fewer than 120 words");

                JSONObject message2 = new JSONObject();
                message2.put("role", "user");
                message2.put("content", keyword);

                JSONArray messagesArray = new JSONArray();
                messagesArray.put(message1);
                messagesArray.put(message2);
                // 构造 API 请求体
                JSONObject requestObj = new JSONObject();
                requestObj.put("messages", messagesArray);
                requestObj.put("temperature", 0.5);
                requestObj.put("top_p", 0.95);
                requestObj.put("frequency_penalty", 0);
                requestObj.put("presence_penalty", 0);
                requestObj.put("max_tokens", 180);
                requestObj.put("stop", null);

                // 发送 API 请求并获取响应结果
                RequestBody body = RequestBody.create(requestObj.toString(), MediaType.get("application/json; charset=utf-8"));
                Request request = new Request.Builder()
                        .url(API_URL)
                        .addHeader("Content-Type", "application/json")
                        .addHeader("api-key", API_KEY)
                        .post(body)
                        .build();
                OkHttpClient client = new OkHttpClient();
                Response response = client.newCall(request).execute();
                String responseString = Objects.requireNonNull(response.body()).string();
                Log.d("SearchTask", "API response: " + responseString);
                Log.d("SearchTask", "RequestBody: " + body);

                // 解析 API 响应结果并返回搜索结果
                JSONObject jsonObj = new JSONObject(responseString);
                Log.d("test", jsonObj.toString());
                JSONArray choicesArray = jsonObj.optJSONArray("choices");
                if (choicesArray != null && choicesArray.length() > 0) {
                    JSONObject choiceObj = choicesArray.getJSONObject(0);
                    if (choiceObj != null) {
                        JSONObject messageObj = choiceObj.getJSONObject("message");
                        return messageObj.getString("content");
                    }

                }
                Log.d("SearchTask", "API response does not contain expected data.");
                return "Error: API response does not contain expected data.";


            } catch (IOException | JSONException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }

        }

        @Override
        protected void onPostExecute(String result) {
            // 确保Fragment已经与Activity关联
            if (isAdded()) {
                // 创建一个新的TextFragment,并将搜索结果传递给它
                TextFragment textFragment = new TextFragment();
                Bundle args = new Bundle();
                args.putString("result", result);
                textFragment.setArguments(args);

                // 使用getChildFragmentManager()方法来替换Fragment
                FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container1, textFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        }
    }
}